<script name="CallbackBind" lang="ts" setup>
import { QQUserInfoRes, QQUserInfo } from '@/types/user'
import { ref } from 'vue'
import { mobileRule, codeRule } from '@/utils/validate'
import { useField, useForm } from 'vee-validate'
import useStore from '@/store'
import { useCountDown } from '@/utils/hooks'
import { useRouter } from 'vue-router'
import Message from '@/components/message'
const router = useRouter()
const { user } = useStore()
const { time, start } = useCountDown(60)
const qqInfo = ref<QQUserInfo>({} as QQUserInfo)
const isLogin = QC.Login.check()
let openId = ''
if (isLogin) {
  // 获取openId
  QC.Login.getMe((id) => {
    openId = id
  })
  // 获取QQ用户信息
  QC.api('get_user_info').success((res: QQUserInfoRes) => {
    // console.log(res)
    qqInfo.value = res.data
  })
}

// 添加表单校验
const { validate } = useForm({
  validationSchema: {
    mobile: mobileRule,
    code: codeRule,
  },
})
const {
  value: mobileValue,
  errorMessage: mobileError,
  validate: mobileValid,
} = useField<string>('mobile')
const { value: codeValue, errorMessage: codeError } = useField<string>('code')

// 发送验证码
const send = async () => {
  if (time.value > 0) return
  // 验证手机号
  const res = await mobileValid()
  if (!res.valid) return
  await user.sendMobileMsg(mobileValue.value)
  start()
}

// 完成绑定
const bind = async () => {
  const res = await validate()
  if (!res.valid) return
  await user.qqBindLogin(openId, mobileValue.value, codeValue.value)
  Message.success('QQ绑定成功')
  router.push('/')
}
</script>
<template>
  <div class="xtx-form">
    <div class="user-info">
      <img :src="qqInfo.figureurl_2" alt="" />
      <p>
        Hi，{{ qqInfo.nickname }} 欢迎来小兔鲜，完成绑定后可以QQ账号一键登录哦~
      </p>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <input
          class="input"
          type="text"
          placeholder="绑定的手机号"
          v-model="mobileValue"
        />
      </div>
      <div class="error">{{ mobileError }}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <input
          class="input"
          type="text"
          placeholder="短信验证码"
          v-model="codeValue"
        />
        <span class="code" @click="send">{{
          time === 0 ? '发送验证码' : `${time}s后发送`
        }}</span>
      </div>
      <div class="error">{{ codeError }}</div>
    </div>
    <a href="javascript:;" class="submit" @click="bind">立即绑定</a>
  </div>
</template>

<style scoped lang="less">
.user-info {
  width: 320px;
  height: 70px;
  margin: 0 auto;
  display: flex;
  background: #f2f2f2;
  align-items: center;
  padding: 0 10px;
  margin-bottom: 25px;
  img {
    background: #f2f2f2;
    width: 50px;
    height: 50px;
  }
  p {
    padding-left: 10px;
  }
}
.code {
  position: absolute;
  right: 0;
  top: 0;
  line-height: 50px;
  width: 80px;
  color: #999;
  &:hover {
    cursor: pointer;
  }
}
</style>
